package com.bulletelc.apollopre.module.main.center.invoice.edit;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.entity.InvoiceBean;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.module.main.MainActivity;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.FoolBar;

import org.json.JSONException;

/**
 * author: lhl
 * date  : 2018/01/23
 * desc  : 添加/编辑发票
 */

public class EditInvoiceActivity extends MVPBaseActivity<EditInvoiceContract.View, EditInvoicePresenter> implements EditInvoiceContract.View,
        View.OnClickListener, FoolBar.ClickCallback {
    // views
    private FoolBar flBar;
    private RadioButton rbCompany;
    private EditText etName, etTaxNo, etBankName, etBankCardNo, etPhone, etAddress,epersonal_username,epersonal_phone,personal_address;
    private CheckBox cbDefault;
    private Button btnSubmit;
    private TextView ettype;
    private LinearLayout linearLayout1,linearLayout2;

    // data
    private int invoiceId = 0; // 发票ID
    private int type=1;//默认选中公司
    @Override
    public int getLayoutRes() {
        return R.layout.invoice_form_activity;
    }
    @Override
    public void assignViews() {

        //公司数据
        ettype=findViewById(R.id.ettype);
        flBar = findViewById(R.id.flBar);
        etName = findViewById(R.id.etName);
        etTaxNo = findViewById(R.id.etTaxNo);
        etBankName = findViewById(R.id.etBankName);
        etBankCardNo = findViewById(R.id.etBankCardNo);
        etPhone = findViewById(R.id.etPhone);
        etAddress = findViewById(R.id.etAddress);
        rbCompany = findViewById(R.id.rbCompany);
        cbDefault = findViewById(R.id.cbDefault);
        btnSubmit = findViewById(R.id.btnSubmit);
        linearLayout1=findViewById(R.id.layout_type_personal);
        linearLayout2=findViewById(R.id.layout_type_company);
        //个人数据
        epersonal_username=findViewById(R.id.epersonal_username);
        epersonal_phone=findViewById(R.id.epersonal_phone);
        personal_address=findViewById(R.id.personal_address);
    }
    @Override
    public void setListener() {
        flBar.setClickCallback(this);
        btnSubmit.setOnClickListener(this);
        ettype.setOnClickListener(this);
    }
    @Override
    public void initData(Bundle savedInstanceState) {
        if(type==1){
            linearLayout2.setVisibility(View.VISIBLE);
            linearLayout1.setVisibility(View.INVISIBLE);
            linearLayout1.setVisibility(View.GONE);
        }else {
            linearLayout1.setVisibility(View.VISIBLE);
            linearLayout2.setVisibility(View.INVISIBLE);
            linearLayout2.setVisibility(View.GONE);
        }
        ettype.setText("类型   "+"公司");
        Intent intent = getIntent();
        if (intent != null) {
            invoiceId = intent.getIntExtra(IntentCode.EXTRA_KEY_INVOICE_ID, 0);
            Log.i("invoiceId", "initData: ");

        }
        rbCompany.setChecked(true);

        if (invoiceId == 0) {
            flBar.setTitle("添加发票");
        } else {
            ettype.setEnabled(false);
            flBar.setTitle("编辑发票");
            presenter.getInvoiceDetail(invoiceId);
        }
    }
    @Override
    protected EditInvoicePresenter createPresenter() {
        return new EditInvoicePresenter();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnSubmit:
                if (invoiceId == 0) {
                    addInvoice();
                }
                else {
                    editInvoice();
                }
                break;
            case R.id.ettype:
                showNormalDialog();
                break;
        }
    }
    private void showNormalDialog() {

        final AlertDialog.Builder builder= new AlertDialog.Builder(this);
        final String[] str={"个人","公司"};
        builder.setSingleChoiceItems(str, type, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(EditInvoiceActivity.this, str[which], Toast.LENGTH_SHORT).show();

                        ettype.setText("类型   "+str[which]);
                        if (str[which]=="个人"){
                            linearLayout2.setVisibility(View.INVISIBLE);
                            linearLayout2.setVisibility(View.GONE);
                            linearLayout1.setVisibility(View.VISIBLE);
                            type=0;
                        }else {
                            linearLayout1.setVisibility(View.INVISIBLE);
                            linearLayout1.setVisibility(View.GONE);
                            linearLayout2.setVisibility(View.VISIBLE);
                            type=1;
                        }

                        //客户点击后，对话框记得消失
                        dialog.dismiss();
                    }
                }

        );

        builder.show();
        /*final String items[] = {"个人", "公司"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this,3);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Toast.makeText(EditInvoiceActivity.this, items[which],
                        Toast.LENGTH_SHORT).show();
                ettype.setText("类型   "+items[which]);
                if (items[which]=="个人"){
                    linearLayout2.setVisibility(View.INVISIBLE);
                    linearLayout2.setVisibility(View.GONE);
                    linearLayout1.setVisibility(View.VISIBLE);
                    type=0;
                }else {
                    linearLayout1.setVisibility(View.INVISIBLE);
                    linearLayout1.setVisibility(View.GONE);
                    linearLayout2.setVisibility(View.VISIBLE);
                    type=1;
                }
            }
        });
        builder.create().show();*/
    }
    @Override
    public void onSuccessAddInvoice() {
        setResult(IntentCode.RESULT_CODE_EDIT_INVOICE_RETURN_LIST);
        finish();
    }

    @Override
    public void onFailAddInvoice(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorAddInvoice(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    @Override
    public void onSuccessInvoiceDetail(InvoiceBean invoiceBean) {
        if(invoiceBean.getType()==0){
            ettype.setText("类型   个人");
            type=0;
            linearLayout2.setVisibility(View.INVISIBLE);
            linearLayout2.setVisibility(View.GONE);
            linearLayout1.setVisibility(View.VISIBLE);
            epersonal_username.setText(invoiceBean.getCompany_name());
            epersonal_phone.setText(invoiceBean.getPhone_no());
            personal_address.setText(invoiceBean.getAddress());
        }else {
            if (invoiceBean != null) {
                etName.setText(invoiceBean.getCompany_name());
                etTaxNo.setText(invoiceBean.getTax_no());
                etBankName.setText(invoiceBean.getBank_name());
                etBankCardNo.setText(invoiceBean.getBank_card_no());
                etPhone.setText(invoiceBean.getPhone_no());
                etAddress.setText(invoiceBean.getAddress());
                cbDefault.setChecked(getIsChecked(invoiceBean.getIs_default()));
            } else {
                Toast.makeText(this, "加载数据有误", Toast.LENGTH_SHORT).show();
            }
        }
    }
    @Override
    public void onFailInvoiceDetail(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorInvoiceDetail(String error) {
        ToastUtil.showLongToast(this,"未知错误，请检查网络");
    }

    @Override
    public void onSuccessEditInvoice() {

        setResult(IntentCode.RESULT_CODE_EDIT_INVOICE_RETURN_LIST);
        finish();
    }

    @Override
    public void onFailEditInvoice(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorEditInvoice(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }
    /**
     * 添加发票
     */
    private void addInvoice() {
        if (type==1){
            String json = null;
            boolean isChecked = cbDefault.isChecked();
            String userId = SharedPreferencesUtil.getString(this, SPKey.SP_USER_ID);
            String name = etName.getText().toString().trim();
            String taxNo = etTaxNo.getText().toString().trim();
            String bankName = etBankName.getText().toString().trim();
            String bankCardNo = etBankCardNo.getText().toString().trim();
            String phone = etPhone.getText().toString().trim();
            String address = etAddress.getText().toString().trim();
            if (name == null || name.length() == 0) {
                etName.setError("请输入名字");
                return;
            }

            if (taxNo==null||taxNo.length()==0) {
                etTaxNo.setError("请输入识别号");
                return;
            }

            if (bankName==null||bankName.length()==0) {
                etBankName.setError("请输入开户行");
                return;
            }

            if (bankCardNo==null||bankCardNo.length()==0) {
                etBankCardNo.setError("请输入银行账号");
                return;
            }

            if (phone==null||phone.length()==0) {
                etPhone.setError("请输入手机号码");
                return;
            }

            if (address==null||address.length()==0) {
                etAddress.setError("请输入地址");
                return;
            }
            org.json.JSONObject obj = new org.json.JSONObject();
            org.json.JSONObject objSub = new org.json.JSONObject();

            try {
                objSub.put("type", 1);
                objSub.put("label", name);
                objSub.put("customer_id", userId);
                //objSub.put("first_name", name.substring(0, 1));
                //objSub.put("last_name", name.substring(1, name.length()));
                objSub.put("first_name", "");
                objSub.put("last_name", "");
                objSub.put("company_name", name);
                objSub.put("bank_name", bankName);
                objSub.put("bank_card_no", bankCardNo);
                objSub.put("tax_no", taxNo);
                objSub.put("phone_no", phone);
                objSub.put("address", address);
                objSub.put("is_default", getIsDefault(isChecked));
                obj.put("CustomerInvoice", objSub);
                json = obj.toString();
                System.out.println("jsondata-----"+json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (json != null) {
                presenter.addInvoice(json);
            } else {
                Toast.makeText(this, "请求参数错误", Toast.LENGTH_SHORT).show();
            }
        }else {
            String json = null;
            boolean isChecked = cbDefault.isChecked();
            String userId = SharedPreferencesUtil.getString(this, SPKey.SP_USER_ID);
            String name = epersonal_username.getText().toString().trim();
            String phone_no = epersonal_phone.getText().toString().trim();
            String address = personal_address.getText().toString().trim();
            if (name == null || name.length() == 0) {
                etName.setError("请输入用户名称");
                return;
            }

            if (phone_no==null||phone_no.length()==0) {
                etTaxNo.setError("请输入手机号码");
                return;
            }

            if (address==null||address.length()==0) {
                etAddress.setError("请输入地址");
                return;
            }
            org.json.JSONObject obj = new org.json.JSONObject();
            org.json.JSONObject objSub = new org.json.JSONObject();
            try {
                objSub.put("type", 0);
                objSub.put("label", name);
                objSub.put("customer_id", userId);
                objSub.put("company_name", name);
                objSub.put("phone_no", phone_no);
                objSub.put("address", address);
                objSub.put("is_default", getIsDefault(isChecked));
                obj.put("CustomerInvoice", objSub);
                json = obj.toString();
                Log.i("data---", json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (json != null) {
                presenter.addInvoice(json);
            } else {
                Toast.makeText(this, "请求参数错误", Toast.LENGTH_SHORT).show();
            }

        }

    }

    /**
     * 编辑发票
     */
    private void editInvoice() {
        if(type==1){
            String json = null;
            String userId = SharedPreferencesUtil.getString(this, SPKey.SP_USER_ID);
            boolean isChecked = cbDefault.isChecked();
            String name = etName.getText().toString().trim();
            String taxNo = etTaxNo.getText().toString().trim();
            String bankName = etBankName.getText().toString().trim();
            String bankCardNo = etBankCardNo.getText().toString().trim();
            String phone = etPhone.getText().toString().trim();
            String address = etAddress.getText().toString().trim();
            if (name == null || name.length() == 0) {
                etName.setError("请输入名字");
                return;
            }
            if (taxNo==null||taxNo.length()==0) {
                etTaxNo.setError("请输入识别号");
                return;
            }

            if (bankName==null||bankName.length()==0) {
                etBankName.setError("请输入开户行");
                return;
            }

            if (bankCardNo==null||bankCardNo.length()==0) {
                etBankCardNo.setError("请输入银行账号");
                return;
            }

            if (phone==null||phone.length()==0) {
                etPhone.setError("请输入手机号码");
                return;
            }

            if (address==null||address.length()==0) {
                etAddress.setError("请输入地址");
                return;
            }

            org.json.JSONObject obj = new org.json.JSONObject();
            org.json.JSONObject objSub = new org.json.JSONObject();
            try {
                objSub.put("type", 1);
                objSub.put("label", name);
                objSub.put("customer_id", userId);
                objSub.put("first_name", name.charAt(0));
                objSub.put("last_name", name.substring(1, name.length()));
                objSub.put("company_name", name);
                objSub.put("bank_name", bankName);
                objSub.put("bank_card_no", bankCardNo);
                objSub.put("tax_no", taxNo);
                objSub.put("phone_no", phone);
                objSub.put("address", address);
                objSub.put("is_default", getIsDefault(isChecked));
                obj.put("CustomerInvoice", objSub);
                json = obj.toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (json != null) {
                presenter.editInvoice(invoiceId, json);
            } else {
                Toast.makeText(this, "提交参数错误", Toast.LENGTH_SHORT).show();
            }
        }else {
            String json = null;
            boolean isChecked = cbDefault.isChecked();
            String userId = SharedPreferencesUtil.getString(this, SPKey.SP_USER_ID);

            String name = epersonal_username.getText().toString().trim();
            String phone_no = epersonal_phone.getText().toString().trim();
            String address = personal_address.getText().toString().trim();
            if (name == null || name.length() == 0) {
                etName.setError("请输入用户名称");
                return;
            }

            if (phone_no==null||phone_no.length()==0) {
                etTaxNo.setError("请输入手机号码");
                return;
            }

            if (address==null||address.length()==0) {
                etAddress.setError("请输入地址");
                return;
            }
            org.json.JSONObject obj = new org.json.JSONObject();
            org.json.JSONObject objSub = new org.json.JSONObject();
            try {
                objSub.put("type", 0);
                objSub.put("label", name);
                objSub.put("customer_id", userId);
                objSub.put("company_name", name);
                objSub.put("phone_no", phone_no);
                objSub.put("address", address);
                objSub.put("is_default", getIsDefault(isChecked));
                obj.put("CustomerInvoice", objSub);
                json = obj.toString();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (json != null) {
                presenter.editInvoice(invoiceId, json);
            } else {
                Toast.makeText(this, "请求参数错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 获取是否默认的值
     *
     * @param isChecked
     * @return
     */
    private int getIsDefault(boolean isChecked) {
        return isChecked ? 1 : 0;
    }

    /**
     * 根据数据判断是否默认
     *
     * @param isDefault
     * @return
     */
    private boolean getIsChecked(int isDefault) {
        return isDefault == 1 ? true : false;
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }
}
